package com.shanghaionstar.carmanage;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.EncryptUtil;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.AppScheduler;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.rxconstants.RxConstants;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.DiscoverActivity;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.IWebType;
import com.shanghaionstar.activity.webview.handler.RemoteControlWebHandler;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.carmanage.adapter.SimpleFragmentPagerAdapter;
import com.shanghaionstar.discover.OVDEmailFragment;
import com.shanghaionstar.discover.WifiHomeFragment;
import com.shanghaionstar.discover.charge.ChargeModeFragment;
import com.shanghaionstar.discover.charge.ChargeModeNotificationFragment;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.iview.ILoginAndOutListener;
import com.shanghaionstar.remote.RemoteFragment;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.weight.TopLayout;

import java.util.ArrayList;
import java.util.List;

import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by 6335yz on 2016/7/24.
 */
@ContentView(R.layout.car_manage)
public class CarManageActivity extends SwipeActivity {
    //    private TabLayout.Tab tb_data_refresh, tb_remote, tb_flow_data, tb_charge_mode;
    @FindViewById(background = R.drawable.common_btn_cancel_bg_click_no_corner)
    private LinearLayout tablayout;
    @FindViewById
    private ViewPager view_pager;
    private SimpleFragmentPagerAdapter simpleFragmentPagerAdapter;
    @FindViewById
    private TextView tb_data_refresh, tb_remote, tb_flow_data, tb_charge_mode;
    @FindViewById
    private TopLayout top_layout;

    private FragmentStatePagerAdapter mFragmentAdapter;

    private List<BaseFragment> mFragmentList = new ArrayList<BaseFragment>();

    private BaseFragment b1 = new CarStatusFragment();
    private BaseFragment b2 = RemoteFragment.newInstance(false);
    private BaseFragment b3 = new CarManager4GFragment();
    private BaseFragment b4 = new ChargeModeFragment();

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    public FragmentManager fm;

//    private LoginUtil loginUtil;

    /**
     * 启动来源标识（是首页还是小O等等）
     */
    public String from;

    public static final String FROM = "from";
    public static final String MRO = "mro";

    private ILoginAndOutListener mLoginLister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fm = getSupportFragmentManager();
//        loginUtil = new LoginUtil();
//        loginUtil.loginAndOutShowView(OnstarApplication.getApplication(), mLoginLister = new ILoginAndOutListener() {
//            @Override
//            public void onLogin() {
//                CarManageActivity.this.onLogin();
//            }
//
//            @Override
//            public void onLoginOut() {
//                CarManageActivity.this.onLoginOut();
//            }
//        });
        loginRegister();
        initFromPage();
    }

    private Subscription mLoginOutRx;

    public void loginRegister() {
        RxSubscriptions.remove(mLoginOutRx);
        mLoginOutRx = RxBus.getDefault()
                .toObserverable(RxConstants.ALL_PAGE_REFRESH, String.class)
                .filter(new Func1<String, Boolean>() {
                    @Override
                    public Boolean call(String s) {
                        return s != null && (s.equalsIgnoreCase(RxConstants.LOGIN_OUT) || s.equalsIgnoreCase(RxConstants.LOGIN_SUCCESS));
                    }
                })
                .subscribeOn(new AppScheduler().backgroundThread())
                .observeOn(new AppScheduler().mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if (ApplicationUtil.getInstance().isLogin()) {
                            CarManageActivity.this.onLogin();
                        } else {
                            CarManageActivity.this.onLoginOut();
                        }
                    }
                });
        RxSubscriptions.add(mLoginOutRx);
        if (ApplicationUtil.getInstance().isLogin()) {
            CarManageActivity.this.onLogin();
        } else {
            CarManageActivity.this.onLoginOut();
        }
//        if (ApplicationUtil.getInstance().isLogin()) {
//            iLoginListener.onLogin();
//        } else {
//            iLoginListener.onLoginOut();
//        }
    }

    /**
     * 获取启动来源
     */
    private void initFromPage() {
        if (getIntent() != null && getIntent().getExtras() != null) {
            from = getIntent().getExtras().getString(FROM);
        }
    }

    @OnClick({R.id.tb_data_refresh, R.id.tb_remote, R.id.tb_flow_data, R.id.tb_charge_mode})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tb_data_refresh:
                view_pager.setCurrentItem(0);
                break;
            case R.id.tb_remote:
                view_pager.setCurrentItem(1);
                break;
            case R.id.tb_flow_data:
                view_pager.setCurrentItem(2);
                break;
            case R.id.tb_charge_mode:
                view_pager.setCurrentItem(3);
                break;
        }
    }

    private void chooseTab(int position) {
        resetBottom();
        switch (position) {
            case 0:
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.CarConditions.getStringValue());
                tb_data_refresh.setTextColor(getResources().getColor(R.color.white));
//                tb_data_refresh.setBackgroundResource(R.drawable.common_btn_bg_click);
                tb_data_refresh.setBackgroundColor(getResources().getColor(R.color.color_1762cb));
                top_layout.setOnRightTextClickLstener(getString(R.string.content_bar_ovd), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BusinessUtil.sendReportByClickType(CarManageActivity.this, FunctionNameFindId.CarConditions_Diagnostics.getStringValue());
                        Intent it = new Intent(CarManageActivity.this, DiscoverActivity.class);
                        it.putExtra(FinalConstants.JUMP_FLAG, OVDEmailFragment.class.getName());
                        startActivity(it);
                    }
                });
                break;
            case 1:
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.CarMngmt_RemoteControl.getStringValue());
                tb_remote.setTextColor(getResources().getColor(R.color.white));
//                tb_remote.setBackgroundResource(R.drawable.common_btn_bg_click);
                tb_remote.setBackgroundColor(getResources().getColor(R.color.color_1762cb));
                top_layout.setOnRightTextClickLstener(getString(R.string.h5_intruction), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BusinessUtil.sendReportByClickType(CarManageActivity.this, FunctionNameFindId.Remote_Introduction.getStringValue());
                        String url;
                        if (DeviceUtil.isChineseLanguage()) {
                            url = Constants.CURRENT_PREFIX_H5_URL + Constants.REMOTEUSERHELP_ZH;
                        } else {
                            url = Constants.CURRENT_PREFIX_H5_URL + Constants.REMOTEUSERHELP_EN;
                        }
//                        Intent intent2 = new Intent(CarManageActivity.this,CommonWebViewActivity.class);
//                        HashMap<String, String> webViewParam = new HashMap<>();
//                        webViewParam.put(OnstarWebViewActivity.URL, url);
//                        webViewParam.put(OnstarWebViewActivity.TITLE, getString(R.string.h5_intruction));
//                        Bundle bundle = new Bundle();
                        WebDataEntity entity = new WebDataEntity();
                        entity.setLinkUrl(url);
                        entity.setClzName(RemoteControlWebHandler.class.getName());
                        entity.setTopTitle(getString(R.string.h5_intruction));
                        entity.what = IWebType.TYPE_NORMAL;
                        CommonWebViewActivity.launchCommonWeb(CarManageActivity.this, entity);
//                        bundle.putParcelable(IWebType.KEY_WEB_DATA,entity);
//                        intent2.putExtras(bundle);
//                        startActivity(intent2);
                    }
                });
                break;
            case 2:
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.CarMngmt_4G.getStringValue());
                tb_flow_data.setTextColor(getResources().getColor(R.color.white));
//                tb_flow_data.setBackgroundResource(R.drawable.common_btn_bg_click);
                tb_flow_data.setBackgroundColor(getResources().getColor(R.color.color_1762cb));
                top_layout.setOnRightTextClickLstener(getString(R.string.option_wifi_manager), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        Intent intent = new Intent(CarManageActivity.this, OrderRecordActivity.class);
//                        Bundle bundle = new Bundle();
//                        bundle.putSerializable(OrderRecordActivity.PACKAGE_TYPE, PackageType.DATA);
//                        intent.putExtras(bundle);
//                        startActivity(intent);
                        BusinessUtil.sendReportByClickType(CarManageActivity.this, FunctionNameFindId.WifiManagement_4G.getStringValue());
                        Intent it = new Intent(CarManageActivity.this, DiscoverActivity.class);
                        it.putExtra(FinalConstants.JUMP_FLAG, WifiHomeFragment.class.getName());
                        startActivity(it);
                    }
                });
                break;
            case 3:
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.CarMngmt_Charge.getStringValue());
                top_layout.setOnRightTextClickLstener(getString(R.string.option_notify_set), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BusinessUtil.sendReportByClickType(CarManageActivity.this, FunctionNameFindId.CarMngmt_Notice_Setting.getStringValue());
                        Bundle bundle = new Bundle();
                        bundle.putString(FinalConstants.JUMP_FLAG, ChargeModeNotificationFragment.class.getName());
                        Intent intent = new Intent(CarManageActivity.this, DiscoverActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
                tb_charge_mode.setBackgroundColor(getResources().getColor(R.color.color_1762cb));
                tb_charge_mode.setTextColor(getResources().getColor(R.color.white));
//                tb_charge_mode.setBackgroundResource(R.drawable.common_btn_bg_click);
                break;
        }
    }

    private void resetBottom() {
        tablayout.setBackgroundResource(R.drawable.common_btn_cancel_bg_click_no_corner);
        tb_data_refresh.setTextColor(getResources().getColor(R.color.color_1762cb));
//        tb_data_refresh.setBackgroundResource(R.drawable.common_btn_cancel_bg_click);
        tb_data_refresh.setBackgroundColor(getResources().getColor(R.color.white));

        tb_remote.setTextColor(getResources().getColor(R.color.color_1762cb));
//        tb_remote.setBackgroundResource(R.drawable.common_btn_cancel_bg_click);
        tb_remote.setBackgroundColor(getResources().getColor(R.color.white));

        tb_flow_data.setTextColor(getResources().getColor(R.color.color_1762cb));
//        tb_flow_data.setBackgroundResource(R.drawable.common_btn_cancel_bg_click);
        tb_flow_data.setBackgroundColor(getResources().getColor(R.color.white));

        tb_charge_mode.setTextColor(getResources().getColor(R.color.color_1762cb));
//        tb_charge_mode.setBackgroundResource(R.drawable.common_btn_cancel_bg_click);
        tb_charge_mode.setBackgroundColor(getResources().getColor(R.color.white));

        if (!ApplicationUtil.getInstance().isGen10()) {
            tb_flow_data.setTextColor(getResources().getColor(R.color.color_a5c5f0));
            tb_flow_data.setClickable(false);
            tb_flow_data.setBackgroundColor(getResources().getColor(R.color.white));
        }
        if (!ApplicationUtil.getInstance().isPhev()) {
            tb_charge_mode.setClickable(false);
            tb_charge_mode.setTextColor(getResources().getColor(R.color.color_a5c5f0));
            tb_charge_mode.setBackgroundColor(getResources().getColor(R.color.white));
        }
    }


    public void onLogin() {
        if (mFragmentList.contains(b1)) {
            return;
        }
        mFragmentList.add(b1);
        mFragmentList.add(b2);
        if (!ApplicationUtil.getInstance().isGen10()) {
            tb_flow_data.setTextColor(getResources().getColor(R.color.color_a5c5f0));
            tb_flow_data.setClickable(false);
            tb_flow_data.setBackgroundColor(getResources().getColor(R.color.white));
        } else {
            mFragmentList.add(b3);
        }
        if (!ApplicationUtil.getInstance().isPhev()) {
            tb_charge_mode.setClickable(false);
            tb_charge_mode.setTextColor(getResources().getColor(R.color.color_a5c5f0));
            tb_charge_mode.setBackgroundColor(getResources().getColor(R.color.white));
        } else {
            mFragmentList.add(b4);
        }
        initViewPager();
        chooseTab(0);
        view_pager.setCurrentItem(0);
    }

    private void initViewPager() {
        mFragmentAdapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return mFragmentList.get(i);
            }

            @Override
            public int getCount() {
                return mFragmentList.size();
            }
        };
        view_pager.setAdapter(mFragmentAdapter);
        view_pager.setOffscreenPageLimit(mFragmentList.size());
        view_pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int state) {

            }

            @Override
            public void onPageScrolled(int position, float offset, int offsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                chooseTab(position);
            }
        });
    }


    public void onLoginOut() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(mLoginOutRx);
//        if (mLoginLister != null) {
//            mLoginLister = null;
//        }
        release();
//        loginUtil = null;
    }

    @Override
    public void finish() {
        super.finish();
        release();
        BusinessUtil.sendReportByClickType(this, FunctionNameFindId.CarMngmt_Return.getStringValue());
    }

    private void release() {
//        if (loginUtil != null) {
//            loginUtil.clear();
//        }
    }
}
